package com.jiyun.controller;

import com.github.pagehelper.PageInfo;
import com.jiyun.mapper.RoomMapper;
import com.jiyun.pojo.Room;
import com.jiyun.pojo.Student;
import com.jiyun.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RequestMapping("/st")
@Controller
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private RoomMapper roomMapper;
    @RequestMapping("/list")
    public String list(Model model, Student student, HttpSession session,
                       @RequestParam(required = false ,defaultValue = "1") Integer pageNum,
                       @RequestParam(required = false ,defaultValue = "3") Integer pageSize){
        PageInfo<Student> pageInfo = studentService.findList2(pageNum,pageSize,student);
        List<Room> roomList = roomMapper.selectAll();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("student",student);
        session.setAttribute("roomList",roomList);
        return "/list";
    }
    @RequestMapping("/toadd")
    public String toAdd(){
        return "add";
    }
    @RequestMapping("/add")
    public String add(MultipartFile file,Student student) throws IOException {
        if (file!=null) {
            String originalFilename = file.getOriginalFilename();
            String url = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            file.transferTo(new File("D:/image/" + url));
            student.setUrl(url);
            studentService.add(student);
        }
        return "redirect:list";
    }
    @RequestMapping("/findById")
    public String findById(Model model,Integer sid){
        Student student = studentService.findById(sid);
        model.addAttribute("student",student);
        return "update";
    }
    @RequestMapping("/update")
    public String update(MultipartFile file,Student student) throws IOException {
        if (file!=null&file.getSize()>0) {
            String originalFilename = file.getOriginalFilename();
            String url = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            file.transferTo(new File("D:/image/" + url));
            student.setUrl(url);
        }studentService.update(student);
        return "redirect:list";
    }
}
